package com.jpxx.netty.marshalling;

import java.io.File;
import java.io.FileOutputStream;
import java.util.concurrent.atomic.AtomicInteger;

import com.jpxx.netty.util.GZipUtilsOK;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

public class ServerHandler extends ChannelHandlerAdapter{  
    
	
	//原子整数
	private AtomicInteger index = new AtomicInteger(1);
	
    @Override  
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {  
    	 Req req = (Req) msg;  
    	 System.out.println("server收到的数据:"+req.getId()+".."+req.getName()+".."+req.getRequestMessage());
    	 
         //解压缩文件  压缩成字节
     	byte[] jieyasuo = GZipUtilsOK.decompress(req.getAttachment());
     	//写出文件
     	//index.getAndIncrement();//+1
    	String writePath = System.getProperty("user.dir")+File.separatorChar+"receive"+File.separatorChar+"00"+index.getAndIncrement()+".jpg";
    	FileOutputStream fos = new FileOutputStream(writePath);
    	fos.write(jieyasuo);
    	fos.close();
    	 
		Resp resp = new Resp();
		resp.setId(req.getId());
		resp.setName("respName:"+req.getId());
		resp.setResponseMessage("server响应内容:"+req.getId());
		ctx.writeAndFlush(resp);//.addListener(ChannelFutureListener.CLOSE)
    }  
      
    @Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		 
	}

	@Override  
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {  
        cause.printStackTrace();  
        ctx.close();  
    }  
  
}  
